import os
import shutil

import grpc
from concurrent import futures
import time
import logging
from typing import Any
from services.dingding_service import DingDingRobotService
from generated import dingding_pb2_grpc
import toml

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class GRPCServer:
    def __init__(self, max_workers: int = 10, port: int = 50051):
        """
        初始化 gRPC 服务器
        :param max_workers: 工作线程数量
        :param port: 服务器端口号
        """



        if not isinstance(port, int) or port < 1 or port > 65535:
            raise ValueError("端口号必须是1-65535之间的整数")

        self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=max_workers))
        self.port = port
        self.services = []
        self._is_running = False

    def register_service(self, service: Any) -> None:
        """
        注册服务
        :param service: 服务实例
        """
        try:
            self.services.append(service)
            if isinstance(service, DingDingRobotService):
                dingding_pb2_grpc.add_DingDingRobotServiceServicer_to_server(service, self.server)
            else:
                raise ValueError(f"不支持的服务类型: {type(service)}")
            logger.info(f"成功注册服务: {type(service).__name__}")
        except Exception as e:
            logger.error(f"服务注册失败: {str(e)}")
            raise

    def start(self) -> None:
        """启动服务器"""
        try:
            addr = f'[::]:{self.port}'
            self.server.add_insecure_port(addr)
            self.server.start()
            self._is_running = True
            logger.info(f"服务器启动在端口 {self.port}")

            while self._is_running:
                time.sleep(60)  # 每分钟检查一次服务器状态
        except Exception as e:
            logger.error(f"服务器运行出错: {str(e)}")
            self.stop()
        except KeyboardInterrupt:
            logger.info("接收到终止信号")
            self.stop()

    def stop(self, grace: int = 5) -> None:
        """
        停止服务器
        :param grace: 优雅关闭等待时间（秒）
        """
        self._is_running = False
        logger.info(f"服务器正在停止，等待 {grace} 秒处理剩余请求...")
        self.server.stop(grace)
        logger.info("服务器已停止")


def main():
    # 读取配置文件
    with open('config.toml', 'r', encoding='utf-8') as f:
        config = toml.load(f)
    logger.info(f'配置:{config}')

    server = GRPCServer()
    ding_ding_robot_service = DingDingRobotService(config['DingDingRobotConfig'])
    server.register_service(ding_ding_robot_service)
    server.start()


if __name__ == '__main__':
    if not os.path.exists('config.toml'):
        shutil.copy('config_example.toml', 'config.toml')
        logger.info('配置文件已创建，请填写配置后重启服务器')
        exit(0)

    main()
